package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * <p>Title: 系统服务的客户端</p>
 * <p>Description: 专门用于向服务器发送特殊指令的</p>
 * <p>Copyright: Copyright (c) 2010</p>
 * <p>Company: GBICC</p>
 * @author : Yuan Zhicheng
 * @version v1.0
 * @date 2010-7-29     */
public class MyHqClinet 
{  
	private String hostName;  
	private int portNum;  
	
	public MyHqClinet(){  
		this.hostName = "10.0.1.25";  
		this.portNum = 8000;  
	}  
	
	private Socket client;
	private BufferedReader in;
	private PrintWriter pw;
	private BufferedReader line;
	
	/** 获取服务器连接   */
	private Socket getSocket(){
		try { 
			client = new Socket(hostName, portNum);
			System.out.println("System client is start OK...");
			
			line = new BufferedReader(new InputStreamReader(System.in));
			pw = new PrintWriter(client.getOutputStream());
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			
		}catch(UnknownHostException e) {  
			System.out.println("未知的主机名："+e.getMessage()); 
		}catch(IOException e) {
			System.out.println("IP="+hostName+" PortNum="+portNum+"IO异常错误："+e.getMessage());
		}
		System.out.println("connected to server");
		System.out.println("Please input your require code:");
		return client;  
	}  
	
	/**  发送消息   */
	public void sendMessage() {
		String command = null;
		try {			
			command = line.readLine();
			pw.println(command);  
			pw.flush(); 
			
			/**测试发送*/
			System.out.println("Your command send to server");
			
			//while (true) {
				String recStr = in.readLine();
				System.out.println("Sys>"+recStr);
			//}
				
			/**测试响应*/
			
		}catch (UnknownHostException e) {
			System.out.println("未知的主机名："+e.getMessage());
		}catch (IOException e) {  
			System.out.println("IO异常错误："+e.getMessage());  
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				in.close();
				pw.close();
				client = null;  
			} catch (IOException e) {
				e.printStackTrace();
			}
		}  
	}
	
	/**  运行客户端   */
	public void runClient(){
		client = getSocket();//获取一个客户端连接
		if (client == null) { 
			pw.print("System Client start exist error!");
			pw.flush();
		}
		
		while (true) {
			sendMessage();
		}
	}
	
	public static void main(String[] args) throws Exception	{
		MyHqClinet client = new MyHqClinet();
		client.runClient();
	}
}